const express = require('express');
const multer = require("multer");
const router = express.Router();
const {server} = require("../../controllers");
const { verifyToken } = require("../verifyToken");

// 生成随机数字
function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 设置存储文件的路径和文件名
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'data/files');
  },
  filename: function (req, file, cb) {
    const fileType = file.originalname.split('.');
    const type = "." + fileType[1];
    const name = Date.now() + randomNum(1, 1000) + type;
    cb(null, name);
  }
});
const upload = multer({ storage: storage });

// 文件上传
router.post("/upload", upload.single("file"), (req, res) => {
  try {

    const data = {
      url: req.file.filename,
      file_name: req.file.originalname.split('.')[0],
      format: req.file.originalname.split('.')[1],
      created_at: new Date()
    }; 
    server.uploadFile(data, res); 
  } catch (error) {
    res.status(500).json({ code: 500, msg: "文件上传失败", error: error.message });
  }
});
// 获取文件
router.post("/getFile", verifyToken, (req, res) => server.getFilePage(req, res));
// 文件移动
router.post("/removeFile", verifyToken, (req, res) => server.removeFile(req, res));
// 删除文件
router.post("/deleteFile", verifyToken, (req, res) => server.deleteFile(req, res));
// 根据图片url删除文件
router.post("/deleteFileByUrl", verifyToken, (req, res) => server.deleteFileByUrl(req, res));


module.exports = router;